package com.blue.controller.system;

import cn.hutool.core.io.FileUtil;
import com.blue.common.annotation.IgnoreToken;
import com.blue.common.entity.ResponseResult;
import com.blue.service.system.IFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author nanjie.chen
 * Created on 2023/9/16
 */
@RestController
@RequestMapping("/system/file")
@Tag(name = "系统文件操作")
@Slf4j
public class FileController {

    @Value("${file.uploadPath}")
    private String uploadPath;

    @Autowired
    private IFileService fileService;


    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public ResponseResult<?> uploadFile(MultipartFile file, @RequestParam(required = false) String business) throws IOException {
        return ResponseResult.okResult(fileService.uploadFile(file, business));
    }

    @GetMapping("/download/{encode}")
    @Operation(summary = "下载文件")
    @IgnoreToken
    public void download(@PathVariable("encode") String encode, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = null;
        try {
            String fileName = new String(Base64.getDecoder().decode(encode), StandardCharsets.UTF_8);
            File file = new File(uploadPath + fileName);
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            outputStream = response.getOutputStream();
            byte[] bytes = FileUtil.readBytes(file);
            outputStream.write(bytes);
        } catch (Exception e) {
            log.error("文件下载失败：{}", e.getMessage());
        } finally {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }
    }
}
